package org.jeecg.modules.typeHandler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class MapIntIntTypeHandler extends BaseTypeHandler<Map<Integer, Integer>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Map<Integer, Integer> map, JdbcType jdbcType) throws SQLException {
        JSONObject jsonObject = new JSONObject();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            jsonObject.put(entry.getKey().toString(), entry.getValue());
        }
        preparedStatement.setString(i, jsonObject.toJSONString());
    }

    private Map<Integer, Integer> getFromJsonObject(JSONObject jsonObject) {
        Map<Integer, Integer> map = new HashMap<>();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            map.put(Integer.parseInt(entry.getKey()), Integer.parseInt(entry.getValue().toString()));
        }
        return map;
    }

    @Override
    public Map<Integer, Integer> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getFromJsonObject(JSONObject.parseObject(resultSet.getString(s)));
    }

    @Override
    public Map<Integer, Integer> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getFromJsonObject(JSONObject.parseObject(resultSet.getString(i)));
    }

    @Override
    public Map<Integer, Integer> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return getFromJsonObject(JSONObject.parseObject(callableStatement.getString(i)));
    }

}
